package com.cats.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.LangUtils;

import android.R.layout;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import com.cats.R;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;

public class LocationMapActivity extends Activity implements 
GooglePlayServicesClient.OnConnectionFailedListener, 
GooglePlayServicesClient.ConnectionCallbacks {

	private GoogleMap map;
	private LocationClient locationClient;
	private ArrayList<LatLng> officeList;
	private final static int
     CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
	private boolean useZipCode = false;
	private String zipCodeString = null;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_location_map);
		officeList = new ArrayList<LatLng>();
		officeList.add(new LatLng(34.711343, -92.344315));
		officeList.add(new LatLng(34.780118, -92.277317));
		officeList.add(new LatLng(34.853399, -92.405321));
		officeList.add(new LatLng(34.802928, -92.428429));
		officeList.add(new LatLng(34.667855, -92.381169));
		
		locationClient = new LocationClient(this, this, this);
		
		map  = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		
		
		useZipCode = false;
		Bundle b = getIntent().getExtras();
		if (b != null) {
			zipCodeString = b.getString("ZIPCODE");
			if (zipCodeString != null && !zipCodeString.isEmpty()) {
				useZipCode = true;
			}		
		}
	}
	
	@Override
	protected void onStart() {
        super.onStart();
        // Connect the client.
        locationClient.connect();
    }
	
	/*
     * Called when the Activity is no longer visible.
     */
    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        locationClient.disconnect();
        super.onStop();
    }
    

	@Override
	public void onConnected(Bundle arg0) {
		System.out.println("[Map]connect success!");
		Geocoder geocoder = new Geocoder(this.getApplicationContext());
		
		if (!useZipCode) {
			final Location mCurrentLocation = locationClient.getLastLocation();	
			final LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
			CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(latLng, 11);
			map.animateCamera(yourLocation);
			for (int i = 0; i < officeList.size(); i++) {
				LatLng officeLatLng = officeList.get(i);
				try {
					ArrayList<Address> addressList = (ArrayList<Address>)geocoder.getFromLocation(officeLatLng.latitude, officeLatLng.longitude, 1);
					Address address = addressList.get(0);
					final String street = address.getAddressLine(0);
					final String city = address.getAddressLine(1);
					map.addMarker(new MarkerOptions().position(officeLatLng)
							.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker))
							.alpha(0.85f)
							.title("CaTS Office (Tap to Navigate)").snippet(street + "  " + city));
					
					final List<Address> myCurrentLocation = (List<Address>) geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
					final String currentStreet = myCurrentLocation.get(0).getAddressLine(0);
					final String currentCity = myCurrentLocation.get(0).getAddressLine(1);		
					map.addMarker(new MarkerOptions().position(latLng).title("Your location").snippet(currentStreet + "  " + currentCity));
					
					map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
			            @Override
			            public void onInfoWindowClick(Marker officeLatLng) {
			            if (!officeLatLng.getTitle().equals("Your location")){
			               Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
			            		    Uri.parse("http://maps.google.com/maps?saddr=" + currentStreet + ", " + currentCity + "&daddr=" + officeLatLng.getSnippet()));
			               startActivity(intent);
			            } else{
			            	//
			            }
			            }
			        });
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					map.addMarker(new MarkerOptions().position(officeLatLng).title("CaTS"));
				}
				
			}			
		}
		else {
			try {
				ArrayList<Address> addressList = (ArrayList<Address>) geocoder.getFromLocationName(zipCodeString, 1);
				if (addressList != null) {
					Address address = addressList.get(0);
					LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
					CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(latLng, 11);
					map.animateCamera(yourLocation);
					
					for (int i = 0; i < officeList.size(); i++) {
						LatLng officeLatLng = officeList.get(i);
						final List<Address> officeLocation = (List<Address>) geocoder.getFromLocation(officeLatLng.latitude, officeLatLng.longitude, 1);
						final String street = officeLocation.get(0).getAddressLine(0);
						final String city = officeLocation.get(0).getAddressLine(1);
						
						map.addMarker(new MarkerOptions().position(officeLatLng)
								.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker))
								.alpha(0.85f)
								.title("CaTS Office (Tap to Navigate)").snippet(street + "  " + city));
						//.title("CaTS Office").snippet(address.getAddressLine(0)));
						
						final List<Address> myCurrentLocation = (List<Address>) geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
						final String currentStreet = myCurrentLocation.get(0).getAddressLine(0);
						final String currentCity = myCurrentLocation.get(0).getAddressLine(1);		
						map.addMarker(new MarkerOptions().position(latLng).title("Zipcode: " + zipCodeString.toString()).snippet(currentStreet + "  " + currentCity));
						
						map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
				            @Override
				            public void onInfoWindowClick(Marker officeLatLng) {
				            if (!officeLatLng.getTitle().equals("Zipcode: " + zipCodeString.toString())){
				               Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
				            		    Uri.parse("http://maps.google.com/maps?saddr=" + currentStreet + ", " + currentCity + "&daddr=" + officeLatLng.getSnippet()));
				               startActivity(intent);
				            } else{
				            	//
				            }
				            }
				        });
						
					}			
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	@Override
	public void onDisconnected() {
		System.out.println("[Map]disconnect success!");		
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		System.out.println("[Map]connect failed!");		
	}
	
	@Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        // Decide what to do based on the original request code
        switch (requestCode) {
            case CONNECTION_FAILURE_RESOLUTION_REQUEST :
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
                switch (resultCode) {
                    case Activity.RESULT_OK :
                    /*
                     * Try the request again
                     */
                    System.out.println("[Map]GPS connect failed");
                    	break;
                }
               break;
            
        }
     }
}